<template>
  <div class="app-container">
    <!-- 🎨 页面标题区域 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">
            <el-icon class="title-icon">
              <Grid />
            </el-icon>
            病虫害管理
          </h1>
          <p class="page-description">管理和维护农作物病虫害及生理性病害信息数据库</p>
        </div>
        <div class="stats-section">
          <div class="stat-card">
            <div class="stat-number">{{ total }}</div>
            <div class="stat-label">总记录数</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 🔍 搜索区域 -->
    <el-card class="search-card" shadow="hover" v-show="showSearch">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon>
              <Search />
            </el-icon>
            筛选查询
          </span>
          <el-button link type="primary" @click="showSearch = !showSearch">
            <el-icon>
              <ArrowUp />
            </el-icon>
          </el-button>
        </div>
      </template>

      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="作物种类ID" prop="categoryId">
              <el-input v-model="queryParams.categoryId" placeholder="请输入作物种类ID" clearable @keyup.enter="handleQuery"
                class="search-input">
                <template #prefix>
                  <el-icon>
                    <LocationInformation />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="病虫害名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入病虫害名称" clearable @keyup.enter="handleQuery"
                class="search-input">
                <template #prefix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="病虫害类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择类型" clearable class="search-input">
                <el-option label="病害" value="病害" />
                <el-option label="虫害" value="虫害" />
                <el-option label="生理性病害" value="生理性病害" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" class="search-buttons">
            <el-button type="primary" icon="Search" @click="handleQuery" class="search-btn">
              搜索查询
            </el-button>
            <el-button icon="Refresh" @click="resetQuery" class="reset-btn">
              重置条件
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 📊 数据表格区域 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="table-header">
          <div class="header-left">
            <span class="card-title">
              <el-icon>
                <Document />
              </el-icon>
              数据列表
            </span>
            <el-tag type="info" class="total-tag">共 {{ total }} 条记录</el-tag>
          </div>

          <!-- 操作按钮组 -->
          <div class="header-actions">
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['pestdisease:pestdisease:add']"
              class="action-btn add-btn">
              新增病虫害
            </el-button>
            <el-button type="success" icon="Edit" :disabled="single" @click="handleUpdate"
              v-hasPermi="['pestdisease:pestdisease:edit']" class="action-btn">
              批量修改
            </el-button>
            <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['pestdisease:pestdisease:remove']" class="action-btn">
              批量删除
            </el-button>
            <el-button type="warning" icon="Download" @click="handleExport"
              v-hasPermi="['pestdisease:pestdisease:export']" class="action-btn">
              导出数据
            </el-button>
            <el-button circle icon="Refresh" @click="getList" class="refresh-btn" title="刷新数据" />
            <el-button circle :icon="showSearch ? 'View' : 'Hide'" @click="showSearch = !showSearch"
              class="toggle-search-btn" :title="showSearch ? '隐藏搜索' : '显示搜索'" />
          </div>
        </div>
      </template>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="pestdiseaseList" @selection-change="handleSelectionChange" class="data-table"
        stripe highlight-current-row>
        <el-table-column type="selection" width="50" align="center" fixed="left" />
        <el-table-column label="序号" type="index" width="60" align="center" fixed="left" />

        <el-table-column label="ID" align="center" prop="id" width="80" />

        <el-table-column label="作物分类" align="center" prop="categoryId" width="100">
          <template #default="scope">
            <el-tag :type="getCategoryTagType(scope.row.categoryId)" size="small">
              {{ getCategoryName(scope.row.categoryId) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="类型" align="center" prop="type" width="80">
          <template #default="scope">
            <el-tag :type="getTypeTagColor(scope.row.type)" size="small">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="名称" align="center" prop="name" width="150" show-overflow-tooltip />

        <el-table-column label="症状描述" align="center" prop="symptoms" width="200">
          <template #default="scope">
            <div class="text-content" :title="scope.row.symptoms">
              {{ truncateText(scope.row.symptoms, 50) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="发生条件" align="center" prop="occurrenceCondition" width="200">
          <template #default="scope">
            <div class="text-content" :title="scope.row.occurrenceCondition">
              {{ truncateText(scope.row.occurrenceCondition, 50) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="防治方法" align="center" prop="controlMethods" width="200">
          <template #default="scope">
            <div class="text-content" :title="scope.row.controlMethods">
              {{ truncateText(scope.row.controlMethods, 50) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="图片" align="center" prop="imageUrls" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.imageUrls" type="success" size="small">
              <el-icon>
                <Picture />
              </el-icon>
              有图片
            </el-tag>
            <el-tag v-else type="info" size="small">
              <el-icon>
                <Picture />
              </el-icon>
              无图片
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="180" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-actions">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)" class="action-link" title="查看详情">
                查看
              </el-button>
              <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['pestdisease:pestdisease:edit']" class="action-link" title="编辑">
                编辑
              </el-button>
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['pestdisease:pestdisease:remove']" class="action-link" title="删除">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" class="table-pagination" />
      </div>
    </el-card>

    <!-- 🔧 添加或修改病虫害对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body class="form-dialog"
      :close-on-click-modal="false">
      <el-form ref="pestdiseaseRef" :model="form" :rules="rules" label-width="120px" class="dialog-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="作物种类ID" prop="categoryId">
              <el-input v-model="form.categoryId" placeholder="请输入作物种类ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="病虫害类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
                <el-option label="病害" value="病害" />
                <el-option label="虫害" value="虫害" />
                <el-option label="生理性病害" value="生理性病害" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="病虫害名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入病虫害名称" />
        </el-form-item>

        <el-form-item label="症状描述" prop="symptoms">
          <el-input v-model="form.symptoms" type="textarea" placeholder="请详细描述症状特征" :autosize="{ minRows: 3, maxRows: 6 }"
            show-word-limit maxlength="500" />
        </el-form-item>

        <el-form-item label="发生条件" prop="occurrenceCondition">
          <el-input v-model="form.occurrenceCondition" type="textarea" placeholder="请描述发生的环境条件"
            :autosize="{ minRows: 3, maxRows: 6 }" show-word-limit maxlength="500" />
        </el-form-item>

        <el-form-item label="防治方法" prop="controlMethods">
          <el-input v-model="form.controlMethods" type="textarea" placeholder="请描述具体的防治措施"
            :autosize="{ minRows: 3, maxRows: 6 }" show-word-limit maxlength="500" />
        </el-form-item>

        <el-form-item label="症状图片URLs" prop="imageUrls">
          <el-input v-model="form.imageUrls" type="textarea" placeholder="请输入图片URL地址，多个地址用逗号分隔"
            :autosize="{ minRows: 2, maxRows: 4 }" />
          <div class="form-tips">
            <el-icon>
              <InfoFilled />
            </el-icon>
            <span>多个图片URL请用英文逗号分隔</span>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel" class="cancel-btn">
            <el-icon>
              <Close />
            </el-icon>
            取 消
          </el-button>
          <el-button type="primary" @click="submitForm" class="submit-btn">
            <el-icon>
              <Check />
            </el-icon>
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Pestdisease">
import {
  Search, ArrowUp, LocationInformation, Document, Grid, Picture,
  View, Edit, Delete, Plus, Refresh, Hide, Download, Check, Close, InfoFilled
} from '@element-plus/icons-vue'
import { listPestdisease, getPestdisease, delPestdisease, addPestdisease, updatePestdisease } from "@/api/agriculture/guo/pestdisease/pestdisease"

const { proxy } = getCurrentInstance()

const pestdiseaseList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: null,
    type: null,
    name: null,
    symptoms: null,
    occurrenceCondition: null,
    controlMethods: null,
    imageUrls: null,
  },
  rules: {
    categoryId: [
      { required: true, message: "作物种类ID不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "病虫害类型不能为空", trigger: "change" }
    ],
    name: [
      { required: true, message: "病虫害名称不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询病虫害管理列表 */
function getList() {
  loading.value = true
  listPestdisease(queryParams.value).then(response => {
    pestdiseaseList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 🎨 辅助方法：获取分类名称
function getCategoryName(categoryId) {
  const categoryMap = {
    1: '小麦',
    2: '玉米',
    3: '水稻',
    4: '棉花'
  }
  return categoryMap[categoryId] || `分类${categoryId}`
}

// 🎨 辅助方法：获取分类标签类型
function getCategoryTagType(categoryId) {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'danger'
  }
  return typeMap[categoryId] || 'info'
}

// 🎨 辅助方法：获取类型标签颜色
function getTypeTagColor(type) {
  switch (type) {
    case '病害': return 'danger'
    case '虫害': return 'warning'
    case '生理性病害': return 'info'
    default: return 'default'
  }
}

// 🎨 辅助方法：文本截断
function truncateText(text, maxLength) {
  if (!text) return '-'
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 🎨 新增：查看详情方法
function handleView(row) {
  // 这里可以跳转到详情页面或显示详情弹窗
  proxy.$router.push({
    path: '/pest-disease-detail',
    query: {
      name: row.name,
      type: row.type
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    categoryId: null,
    type: null,
    name: null,
    symptoms: null,
    occurrenceCondition: null,
    controlMethods: null,
    imageUrls: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("pestdiseaseRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加病虫害信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPestdisease(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改病虫害信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["pestdiseaseRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePestdisease(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPestdisease(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除病虫害管理编号为"' + _ids + '"的数据项？').then(function () {
    return delPestdisease(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('pestdisease/pestdisease/export', {
    ...queryParams.value
  }, `pestdisease_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
/* 🎨 整体容器样式 */
.app-container {
  padding: 20px;
  background: #f5f7fa;
}

/* 🎨 页面头部样式 */
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  margin-bottom: 20px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 30px;
  color: white;
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 32px;
}

.page-description {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.stats-section {
  display: flex;
  gap: 20px;
}

.stat-card {
  text-align: center;
  padding: 12px 20px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.8;
}

/* 🎨 卡片样式 - 简化版本 */
.search-card,
.table-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 🎨 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
}

/* 🎨 搜索表单样式 */
.search-form {
  padding: 10px 0;
}

.search-input {
  width: 100%;
}

.search-buttons {
  text-align: center;
  margin-top: 10px;
}

.search-btn {
  background: linear-gradient(135deg, #409eff, #529eff);
  border: none;
  padding: 10px 24px;
  border-radius: 6px;
  margin-right: 12px;
}

.reset-btn {
  padding: 10px 24px;
  border-radius: 6px;
}

/* 🎨 表格头部样式 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.total-tag {
  background: #f0f9ff;
  color: #0369a1;
  border: 1px solid #bae6fd;
}

.header-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
}

.add-btn {
  background: linear-gradient(135deg, #67c23a, #85ce61);
  border: none;
  color: white;
}

.refresh-btn,
.toggle-search-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  color: #606266;
}

.refresh-btn:hover,
.toggle-search-btn:hover {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

/* 🎨 表格样式 */
.data-table {
  border-radius: 8px;
  overflow: hidden;
  background: white;
}

.data-table :deep(.el-table__header) {
  background: #f8fafc;
}

.data-table :deep(.el-table__header th) {
  background: #f8fafc !important;
  color: #374151;
  font-weight: 600;
  border-bottom: 2px solid #e5e7eb;
}

.data-table :deep(.el-table__row:hover) {
  background: #f0f9ff !important;
}

.text-content {
  line-height: 1.5;
  color: #4b5563;
}

.table-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-link {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 🎨 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.table-pagination {
  background: white;
  padding: 16px;
  border-radius: 8px;
}

/* 🎨 弹窗样式 */
.form-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

.form-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 24px;
  margin: 0;
}

.form-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

.dialog-form {
  padding: 24px;
}

.form-tips {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 6px;
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  padding: 16px 24px;
  background: #f8fafc;
  border-top: 1px solid #e5e7eb;
  text-align: right;
  gap: 12px;
  display: flex;
  justify-content: flex-end;
}

.submit-btn {
  background: linear-gradient(135deg, #409eff, #529eff);
  border: none;
  padding: 10px 24px;
}

.cancel-btn {
  padding: 10px 24px;
}

/* 🎨 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 12px;
  }

  .header-content {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }

  .table-header {
    flex-direction: column;
    align-items: stretch;
  }

  .header-actions {
    justify-content: center;
  }

  .action-btn {
    flex: 1;
    min-width: 120px;
  }

  .search-form :deep(.el-col) {
    margin-bottom: 16px;
  }
}
</style>